package com.lysj.bhp.api.controller;

import com.lysj.bhp.api.base.ApiContent;
import com.lysj.bhp.borrowing.domain.BorrowingInstallment;
import com.lysj.bhp.borrowing.domain.BorrowingRecord;
import com.lysj.bhp.borrowing.domain.CreditFile;
import com.lysj.bhp.borrowing.dto.BorrowingRecordDto;
import com.lysj.bhp.borrowing.vo.BorrowingRecordVo;
import com.lysj.bhp.borrowing.vo.CurrentRepayVo;
import com.lysj.bhp.borrowing.vo.UserCreditFileVo;
import com.lysj.bhp.util.random.FormatUtil;
import com.lysj.bhp.util.respmap.RespMapUtil;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/v2/user")
@Api(value = "ApiBorrowingController", tags = "借贷模块接口")
public class ApiBorrowingRecordController extends ApiContent {

    @InitBinder
    public void InitBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }

    @ApiOperation(value = "借款明细记录(申请中)", notes = "查询条件起始时间:begin_applyDate,end_applyDate;" +
            "申请单状态：1:申请中||2.还款中||3：已结清,checkStatus ;//审核状态:1：申请中||-1:放款失败||2：审核中")
    @GetMapping("/borrowing_apply_record_list")
    public Resp borrowingApplyRecordList(BorrowingRecordDto model) {
        Page<BorrowingRecordVo> borrowingApplyRecordVoPage = borrowingClosedRecordVoPage(model, 1);
        for (BorrowingRecordVo borrowingRecordVo : borrowingApplyRecordVoPage) {
            //借款金额转CNY
            borrowingRecordVo.setBorrowingMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingRecordVo.getBorrowingType(),borrowingRecordVo.getBorrowingMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
            //抵押金额转CNY
            borrowingRecordVo.setMortgageMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingRecordVo.getMortgageType() , borrowingRecordVo.getMortgageMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        Map<String, Object> respMap = RespMapUtil.respMap(borrowingApplyRecordVoPage.getTotalPages(), borrowingApplyRecordVoPage.getContent());
        Integer[] res = {1, 2, -1};
        respMap.put("select", res);
        return new Resp(respMap);
    }

    @ApiOperation(value = "借款明细记录(已结清中)", notes = "查询条件起始时间:begin_applyDate,end_applyDate;" +
            "申请单状态：默认3：已结清, defaultStatus;//是否逾期: 1：已逾期||2:正常状态")
    @GetMapping("/borrowing_closed_record_list")
    public Resp borrowingClosedRecordList(BorrowingRecordDto model) {

        Page<BorrowingRecordVo> borrowingRecordVoPage = borrowingClosedRecordVoPage(model, 3);

        for (BorrowingRecordVo borrowingClosedRecordVo : borrowingRecordVoPage) {
            //若还款方式为到期还款则进度为0/1
            BorrowingRecord borrowingRecord1 = borrowingContent.borrowingRecordRepository.findOne(borrowingClosedRecordVo.getBorrowingRecordId());
            if (1 == borrowingRecord1.getRefundWay()) {
                borrowingClosedRecordVo.setProgressInfo(borrowingClosedRecordVo.getProgress() + "/1");
            } else {
                borrowingClosedRecordVo.setProgressInfo(borrowingClosedRecordVo.getProgress() + "/" + borrowingClosedRecordVo.getDeadline());
            } //获取借款记录对应的借款明细
            List<BorrowingInstallment> borrowingInstallmentList = borrowingContent.borrowingInstallmentRepository.findByUserIdAndBorrowingRecordId(currentUser().getUserId(), borrowingClosedRecordVo.getBorrowingRecordId());
            BigDecimal totolPaidDebtMoney = new BigDecimal(BigInteger.ZERO);
            BigDecimal totolReturnMoney = new BigDecimal(BigInteger.ZERO);
            for (int i = 0; i < borrowingInstallmentList.size(); i++) {
                //借款单的违约金额(每一期的借款明细违约金累加)
                totolPaidDebtMoney = totolPaidDebtMoney.add(borrowingInstallmentList.get(i).getDefaultMoney());
                //借款单的还款金额(每一期的借款明细的还款金额+违约金)
                totolReturnMoney = totolReturnMoney.add(borrowingInstallmentList.get(i).getActualRepaymentMoney());
                //结清时间
                borrowingClosedRecordVo.setClosedDate(borrowingInstallmentList.get(i).getActualRepaymentDate());
            }
            //已还金额
            borrowingClosedRecordVo.setOffDebtMoney(totolReturnMoney);
            //违约金额
            borrowingClosedRecordVo.setDefaultMoney(totolPaidDebtMoney);
            //抵押金额转CNY
            borrowingClosedRecordVo.setMortgageMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingClosedRecordVo.getMortgageType(),borrowingClosedRecordVo.getMortgageMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
            //借款金额转CNY
            borrowingClosedRecordVo.setBorrowingMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingClosedRecordVo.getBorrowingType(),borrowingClosedRecordVo.getBorrowingMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
            //已还金额转CNY
            borrowingClosedRecordVo.setOffDebtMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingClosedRecordVo.getBorrowingType(),totolReturnMoney).setScale(2, BigDecimal.ROUND_HALF_UP));
            //违约金额转CNY
            borrowingClosedRecordVo.setDefaultMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingClosedRecordVo.getBorrowingType(),totolPaidDebtMoney).setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        Map<String, Object> respMap = RespMapUtil.respMap(borrowingRecordVoPage.getTotalPages(), borrowingRecordVoPage.getContent());
        Integer[] res = {1, 2};
        respMap.put("select", res);
        return new Resp(respMap);
    }


    @ApiOperation(value = "借款明细记录(还款中)", notes = "查询条件起始时间:begin_applyDate,end_applyDate;" +
            "申请单状态：默认2：还款中, defaultStatus;//是否逾期: 1：已逾期||2:正常状态")
    @GetMapping("/borrowing_payment_record_list")
    public Resp borrowingPaymentRecordList(BorrowingRecordDto model) {

        Page<BorrowingRecordVo> borrowingPaymentRecordVoPage = borrowingClosedRecordVoPage(model, 2);
        for (BorrowingRecordVo borrowingPaymentRecordVo : borrowingPaymentRecordVoPage) {
            //若还款方式为到期还款则进度为0/1
            BorrowingRecord borrowingRecord1 = borrowingContent.borrowingRecordRepository.findOne(borrowingPaymentRecordVo.getBorrowingRecordId());
            if (1 == borrowingRecord1.getRefundWay()) {
                borrowingPaymentRecordVo.setProgressInfo("0/1");
            } else {
                borrowingPaymentRecordVo.setProgressInfo(borrowingPaymentRecordVo.getProgress() + "/" + borrowingPaymentRecordVo.getDeadline());
            }
            //查询出借贷记录,获取当前期数
            BorrowingRecord borrowingRecord = borrowingContent.borrowingRecordRepository.findOne(borrowingPaymentRecordVo.getBorrowingRecordId());
            //获取借款记录当前期的还款明细
            BorrowingInstallment borrowingInstallment = borrowingContent.borrowingInstallmentRepository.findByUserIdAndBorrowingRecordIdAndNper(currentUser().getUserId(), borrowingPaymentRecordVo.getBorrowingRecordId(), borrowingRecord.getProgress() + 1);
            //还款时间
            borrowingPaymentRecordVo.setReturnMoneyDate(borrowingInstallment.getEndRepaymentDate());
            //本期应还(本金+利息)
            borrowingPaymentRecordVo.setCurrentDebtMoney(borrowingInstallment.getReturnMoney().add(borrowingInstallment.getReturnDividend()).add(borrowingInstallment.getDefaultMoney()));
            //已还金额
            BigDecimal totolOffPaidDebtMoney = new BigDecimal(BigInteger.ZERO);
            for (int i = 1; i <= borrowingRecord.getProgress(); i++) {
                BorrowingInstallment borrowingInstallment1 = borrowingContent.borrowingInstallmentRepository.findByUserIdAndBorrowingRecordIdAndNper(currentUser().getUserId(), borrowingPaymentRecordVo.getBorrowingRecordId(), i);
                totolOffPaidDebtMoney = totolOffPaidDebtMoney.add(borrowingInstallment1.getActualRepaymentMoney());
            }
            borrowingPaymentRecordVo.setOffDebtMoney(totolOffPaidDebtMoney);
            //未还金额
            BigDecimal totolNoPaidDebtMoney = new BigDecimal(BigInteger.ZERO);
            if (borrowingRecord.getRefundWay() == 1) {
                BorrowingInstallment borrowingInstallment1 = borrowingContent.borrowingInstallmentRepository.findByUserIdAndBorrowingRecordIdAndNper(currentUser().getUserId(), borrowingPaymentRecordVo.getBorrowingRecordId(), 1);
                totolNoPaidDebtMoney = totolNoPaidDebtMoney.add(borrowingInstallment1.getReturnMoney()).add(borrowingInstallment1.getReturnDividend().add(borrowingInstallment1.getDefaultMoney()));
            } else {
                for (int i = borrowingRecord.getProgress() + 1; i <= borrowingRecord.getDeadline(); i++) {
                    BorrowingInstallment borrowingInstallment1 = borrowingContent.borrowingInstallmentRepository.findByUserIdAndBorrowingRecordIdAndNper(currentUser().getUserId(), borrowingPaymentRecordVo.getBorrowingRecordId(), i);
                    totolNoPaidDebtMoney = totolNoPaidDebtMoney.add(borrowingInstallment1.getReturnMoney()).add(borrowingInstallment1.getReturnDividend().add(borrowingInstallment1.getDefaultMoney()));
                }
            }

            //抵押金额转CNY
            borrowingPaymentRecordVo.setMortgageMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingPaymentRecordVo.getMortgageType(),borrowingPaymentRecordVo.getMortgageMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
            borrowingPaymentRecordVo.setNoDebtMoney(totolNoPaidDebtMoney);
            //借款金额转CNY
            borrowingPaymentRecordVo.setBorrowingMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingPaymentRecordVo.getBorrowingType(),borrowingPaymentRecordVo.getBorrowingMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
            //本期应还转CNY
            borrowingPaymentRecordVo.setCurrentDebtMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingPaymentRecordVo.getBorrowingType(),borrowingPaymentRecordVo.getCurrentDebtMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
            //已还金额转CNY
            borrowingPaymentRecordVo.setOffDebtMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingPaymentRecordVo.getBorrowingType(),borrowingPaymentRecordVo.getOffDebtMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
            //未还金额转CNY
            borrowingPaymentRecordVo.setNoDebtMoneyCny(exchangeRateService.qtumMoneyToCny(borrowingPaymentRecordVo.getBorrowingType(),borrowingPaymentRecordVo.getNoDebtMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        Map<String, Object> respMap = RespMapUtil.respMap(borrowingPaymentRecordVoPage.getTotalPages(), borrowingPaymentRecordVoPage.getContent());
        //1.
        Integer[] res = {1, 2};
        respMap.put("select", res);
        return new Resp(respMap);
    }


    @ApiOperation(value = "显示借款信息")
    @GetMapping("/borrowing_credit_info")
    public Resp borrowingCreditInfo() {
        Map<String, Object> map = new HashMap<>();
        List<UserCreditFileVo> userCreditFileVoList = new LinkedList<>();
        //BTC借款信息
        UserCreditFileVo btcCreditFileVo = creditFileInfo(10);
        userCreditFileVoList.add(btcCreditFileVo);
        //ETH借款信息
        UserCreditFileVo ethCreditFileVo = creditFileInfo(20);
        userCreditFileVoList.add(ethCreditFileVo);
        //BHPC借款信息
        UserCreditFileVo bhpcCreditFileVo = creditFileInfo(100);
        userCreditFileVoList.add(bhpcCreditFileVo);
        map.put("userCreditFileVoList", userCreditFileVoList);
        //借款总额
        BigDecimal totalBtcBalance = btcCreditFileVo.getBorrowingBalance().multiply(exchangeRateService.bitcoinToCnyRate());
        BigDecimal totalEthBalance = ethCreditFileVo.getBorrowingBalance().multiply(exchangeRateService.ethToCnyRate());
        BigDecimal totalBhpcBalance = bhpcCreditFileVo.getBorrowingBalance().multiply(exchangeRateService.bhpcToCnyRate());
        map.put("totalBalance", totalBtcBalance.add(totalEthBalance).add(totalBhpcBalance).setScale(4, BigDecimal.ROUND_HALF_UP));

        CurrentRepayVo currentRepayVo = new CurrentRepayVo();
        //
        Integer[] status = {1, 2, 3};
        Long borrowingRecordRow = borrowingContent.borrowingRecordRepository.BorrowingRecordRow(currentUser().getUserId(), status);
        //获取最近还款
        List<BorrowingInstallment> borrowingInstallmentList = borrowingContent.borrowingInstallmentRepository.findByUserIdAndActualRepaymentDateNullOrderByEndRepaymentDateAsc(currentUser().getUserId());
        if (borrowingRecordRow == 0) {
            map.put("isExist", -2);
        } else if (borrowingInstallmentList.size() > 0) {
            BorrowingRecord borrowingRecord = borrowingContent.borrowingRecordRepository.findOne(borrowingInstallmentList.get(0).getBorrowingRecordId());
            //借款id
            currentRepayVo.setBorrowingRecordId(borrowingRecord.getBorrowingRecordId());
            //借款编号
            currentRepayVo.setBorrowingOrderNo(borrowingRecord.getBorrowingOrderNo());
            //还款金额(所需归还本金+所需归还利息+违约金)
            currentRepayVo.setRepayMoney(borrowingInstallmentList.get(0).getReturnMoney().add(borrowingInstallmentList.get(0).getReturnDividend()).add(borrowingInstallmentList.get(0).getDefaultMoney()).setScale(6, BigDecimal.ROUND_HALF_UP));
            //还款进度
            if (1 == borrowingRecord.getRefundWay()) {
                currentRepayVo.setProgressInfo("0/1");
            } else {
                currentRepayVo.setProgressInfo(borrowingRecord.getProgress() + "/" + borrowingRecord.getDeadline());
            }
            //还款日期
            currentRepayVo.setRepayDate(borrowingInstallmentList.get(0).getEndRepaymentDate());
            //还款金额
            currentRepayVo.setBorrowingType(borrowingRecord.getBorrowingType());
            //逾期
            Date nowDate = FormatUtil.getDayEndDay(new Date());
            if (nowDate.equals(borrowingInstallmentList.get(0).getEndRepaymentDate())) {
                currentRepayVo.setDefaultState(3);
            } else {
                currentRepayVo.setDefaultState(borrowingInstallmentList.get(0).getDefaultState());
            }
            //存在
            map.put("isExist", 1);
        } else if (borrowingInstallmentList.size() == 0) {
            Integer[] newStatus1 = {1,2};
            Long row = borrowingContent.borrowingRecordRepository.BorrowingRecordApproveRow(currentUser().getUserId(), newStatus1);
            if (row > 0) {
                map.put("isExist", -3);
            } else {
                map.put("isExist", -1);
            }
        }

        map.put("currentRepayVo", currentRepayVo);
        return new Resp(map);
    }


    /**
     * @author drj
     * @date 2018/8/22 19:51
     * @Description：还款,已结款记录,判空以及查询操作
     */
    private Page<BorrowingRecordVo> borrowingClosedRecordVoPage(BorrowingRecordDto model, Integer status) {
        //查询条件数据为空,进行初始化操作
        if (ParamUtil.isBlack(model.getLimit())) {
            model.setLimit(10);
        }
        if (ParamUtil.isBlack(model.getPage())) {
            model.setPage(0);
        }
        if (ParamUtil.isBlack(model.getBorrowingOrderNo())) {
            model.setBorrowingOrderNo("");
        }
        if (model.getBegin_applyDate() == null) {
            model.setBegin_applyDate(FormatUtil.addDay(new Date(), -30));
        } else {
            model.setBegin_applyDate(FormatUtil.getDayStartDay(model.getBegin_applyDate()));
        }
        if (model.getEnd_applyDate() == null) {
            model.setEnd_applyDate(FormatUtil.getDayEndDay(new Date())); //  获取到今天的结束
        } else {
            model.setEnd_applyDate(FormatUtil.getDayEndDay(model.getEnd_applyDate()));
        }
        //获取根据时间以及借款记录状态查询出的借款记录
        Pageable pageable = new PageRequest(model.getPage(), model.getLimit(), new Sort(Sort.Direction.DESC, "applyDate"));
        Page<BorrowingRecordVo> rechargeRecordPagepage = null;
        if (!ParamUtil.isBlack(model.getDefaultStatus())) {
            rechargeRecordPagepage = borrowingContent.borrowingRecordRepository.findBorrowingClosedRecord(pageable, status, model.getDefaultStatus(), model.getBegin_applyDate(), model.getEnd_applyDate(), currentUser().getUserId(), model.getBorrowingOrderNo());
        } else if (!ParamUtil.isBlack(model.getCheckStatus())) {
            rechargeRecordPagepage = borrowingContent.borrowingRecordRepository.findBorrowingApplyRecord(pageable, status, model.getCheckStatus(), model.getBegin_applyDate(), model.getEnd_applyDate(), currentUser().getUserId(), model.getBorrowingOrderNo());
            ;
        } else {
            rechargeRecordPagepage = borrowingContent.borrowingRecordRepository.findBorrowingAllClosedRecord(pageable, status, model.getBegin_applyDate(), model.getEnd_applyDate(), currentUser().getUserId(), model.getBorrowingOrderNo());
        }
        return rechargeRecordPagepage;
    }


    /**
     * @author drj
     * @date 2018/8/22 19:51
     * @Description：构建对应币种的借款记录信息
     */
    private UserCreditFileVo creditFileInfo(Integer walletType) {
        UserCreditFileVo userCreditFileVo = new UserCreditFileVo();
        CreditFile creditFile = borrowingContent.creditFileRepository.findByUserIdAndWalletType(currentUser().getUserId(), walletType);
        if (null != creditFile) {
            userCreditFileVo.setBorrowingAmount(creditFile.getBorrowingAmount());
            userCreditFileVo.setBorrowingBalance(creditFile.getBorrowingBalance());
            userCreditFileVo.setAdvanceAmount(creditFile.getAdvanceAmount());
            userCreditFileVo.setAdvanceMoney(creditFile.getAdvanceBalance());
            userCreditFileVo.setLateAmount(creditFile.getOverduePayOffAmount());
            userCreditFileVo.setLateMoney(creditFile.getOverduePayOffBalance());
        }
        userCreditFileVo.setWalletType(walletType);
        return userCreditFileVo;
    }


}
